/**
 * \brief  Client-side cpu session interface
 * \author Christian Helmuth
 * \date   2006-07-12
 */

/*
 * Copyright (C) 2006-2009 Christian Helmuth
 * Genode Labs, Feske & Helmuth Systementwicklung GbR
 *
 * This file is part of the Genode OS framework, which is distributed
 * under the terms of the GNU General Public License version 2.
 */

#ifndef _INCLUDE__CPU_SESSION__CLIENT_H_
#define _INCLUDE__CPU_SESSION__CLIENT_H_

#include <cpu_session/capability.h>
#include <base/ipc.h>
#include <base/lock.h>

namespace Genode {

	class Cpu_session_client : public Cpu_session
	{
		private:

			Msgbuf<THREAD_NAME_LEN + 32> _snd_msg, _rcv_msg;
			Ipc_client                   _ipc_client;
			Lock                         _lock;

		public:

			explicit Cpu_session_client(Cpu_session_capability session)
			: _ipc_client(session, &_snd_msg, &_rcv_msg) { }

			Thread_capability create_thread(const char* name)
			{
				Lock::Guard lock_guard(_lock);
				Thread_capability result;

				switch (_ipc_client << CREATE_THREAD << Buffer(name)
				                    << IPC_CALL
				                    >> result) {

				case -1: throw Thread_creation_failed();
				default: break;
				}

				return result;
			}

			void kill_thread(Thread_capability thread)
			{
				Lock::Guard lock_guard(_lock);
				_ipc_client << KILL_THREAD << thread << IPC_CALL;
			}

			Thread_capability first()
			{
				Lock::Guard lock_guard(_lock);
				Thread_capability result;
				_ipc_client << FIRST << IPC_CALL >> result;
				return result;
			}

			Thread_capability next(Thread_capability curr)
			{
				Lock::Guard lock_guard(_lock);
				Thread_capability result;
				_ipc_client << NEXT << curr << IPC_CALL >> result;
				return result;
			}

			int set_pager(Thread_capability thread, Thread_capability pager)
			{
				Lock::Guard lock_guard(_lock);
				return (_ipc_client << SET_PAGER << thread << pager
				                    << IPC_CALL);
			}

			int start(Thread_capability thread, addr_t ip, addr_t sp)
			{
				Lock::Guard lock_guard(_lock);
				return (_ipc_client << START << thread << ip << sp
				                    << IPC_CALL);
			}

			void cancel_blocking(Thread_capability thread)
			{
				Lock::Guard lock_guard(_lock);
				_ipc_client << CANCEL_BLOCKING << thread << IPC_CALL;
			}

			int name(Thread_capability thread, char *name_dst, size_t name_len)
			{
				Lock::Guard lock_guard(_lock);
				Buffer name;
				int res = _ipc_client << NAME << thread << IPC_CALL >> name;
				strncpy(name_dst, name.addr(), name_len);
				return res;
			}

			int state(Thread_capability thread, Thread_state *dst_state)
			{
				Lock::Guard lock_guard(_lock);
				return (_ipc_client << STATE << thread << IPC_CALL >> *dst_state);
			}
	};
}

#endif /* _INCLUDE__CPU_SESSION__CLIENT_H_ */
